package org.example.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.*;
import org.example.mapper.*;
import org.example.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ============================================================<br>
 * <p> ProjectName ：dianguanjiaexportdata </p>
 * <p> @author dongjianzhao </p>
 * <p> @date 2023/3/18 </p>
 * <p> @version ：1.0 </p>
 * ============================================================<br>
 * <p>
 * Contract  合同的数据的适配
 * </p>
 * ============================================================<br>
 */
@Service
@Slf4j
public class ContractAdapterImpl {
    @Autowired
    private TempContractMapper tempContractMapper;
    @Autowired
    private TempContractInfoMapper tempContractInfoMapper;
    @Autowired
    private IesContractConsnoMapper iesContractConsnoMapper;
    @Autowired
    private IesContractInfoMapper iesContractInfoMapper;
    @Autowired
    private TempPriceMapper tempPriceMapper;
    @Autowired
    private IesCustMapper iesCustMapper;
    @Autowired
    private IesContractStationMapper iesContractStationMapper;
    @Autowired
    private IesConttransfMapper iesConttransfMapper;
    @Autowired
    private TempCtrtequipMapper tempCtrtequipMapper;
    @Autowired
    private IesContractComboPriceMapper iesContractComboPriceMapper;
    public void adapter() {
        SnowFlake sf=new SnowFlake(2,3);
       // 表ies_contract_consno (运维客户合同对应营销户号)
       //  addIesContractConsno();
//        表ies_contract_info (运维客户合同表)
       //  addIesContractInfo(sf);
      //  表ies_contract_station (运维客户配电室)
      //表ies_conttransf (运维客户变压器)

      //  addTempCtrtequip(sf);


      //  addIesContractComboPrice(sf);

       // updateInspectionExecunum();
    }

    private void updateInspectionExecunum() {
      List<IesContractInfo> list= iesContractInfoMapper.selectAll();

        list.forEach(l->{
            String contractids = l.getContractids();
            Map<String,Object> param=new HashMap<>();
            param.put("ciId",contractids);

            List<TempContract> tempContracts = tempContractMapper.selectByMap(param);
            TempContract tempContract = tempContracts.get(0);
            //已经巡检
            Long inspectionExecunum = tempContract.getInspectionExecunum();
            //巡检次数
            Long inspectionNum = tempContract.getInspectionNum();
            if(inspectionExecunum!=null &&inspectionNum!=null){
                Long i= inspectionNum-inspectionExecunum;
                l.setRepairnum(inspectionNum.intValue());
                l.setRemainnumber(i.intValue());
                iesContractInfoMapper.updateForRepairnum(inspectionNum.intValue(),i.intValue(),contractids);
            }
        });
    }

    /**
     * 同步运维客户服务套餐
     * @param sf
     */
    private void addIesContractComboPrice(SnowFlake sf) {
        List<TempPrice> list=tempPriceMapper.selectPriceTypeNot05();
        list.forEach(l->{
            Map<String,Object> p=new HashMap<>();
            p.put("contractids",l.getCiId());
            List<IesContractInfo> iesContractInfos = iesContractInfoMapper.selectByMap(p);
            if(iesContractInfos!=null&&iesContractInfos.size()>0){
                IesContractComboPrice ies=new IesContractComboPrice();
                ies.setContractpriceid(sf.nextId());
                /**
                 * 合同id
                 */
                ies.setContractid(iesContractInfos.get(0).getContractid());
                /**
                 * 价格id
                 */
                ies.setPriceid(Long.valueOf(l.getPriceType()));
                /**
                 * 变压器容量范围
                 */
                ies.setCapacity(l.getPriceTypeName());
                Map<String,Object> param=new HashMap<>();
                param.put("ciid",l.getCiId());
                param.put("ppid",l.getPpId());
                List<TempCtrtequip> tempCtrtequips = tempCtrtequipMapper.selectByMap(param);
                /**
                 * 变压器台数
                 */
                ies.setDevnum(tempCtrtequips.size());
                /**
                 * 星会员、铂金（单台设备费用）
                 */
                ies.setDevbasiccost(l.getPrice().doubleValue());
                /**
                 * 根据容量范围查询抢修类型编码、抢修次数控制
                 */
               //Map<String,String>  tempPrice=tempPriceMapper.selectEmertypecode(l.getT1(),l.getT2());
                Map<String,String>  tempPrice=tempPriceMapper.selectEmertypecode(Integer.valueOf(l.getPriceType())+"");
                 if(tempPrice!=null){
                     /**
                      * 抢修类型编码
                      */
                     ies.setEmertypecode(tempPrice.get("emertypecode"));
                     /**
                      * 抢修次数控制
                      */
                     ies.setEmertype(tempPrice.get("emertype"));
                 }

                /**
                 * 超出费用
                 */
                ies.setExcesscost(l.getExceedPrice().doubleValue());
                /**
                 * 备注
                 */
                ies.setRemarks("");
                log.info("ies:{}", JSONObject.toJSON(ies));
                iesContractComboPriceMapper.insert(ies);
            }
        });
    }

    /**
     * 添加配电室和变压器的数据
     */
    private void addTempCtrtequip(SnowFlake sf) {
        List<TempCtrtequip> list=tempCtrtequipMapper.selectAll();
        list.forEach(l->{
            //配电室
            if("00".equals(l.getInstallType())){

                Map<String,Object> p=new HashMap<>();
                p.put("contractids",l.getCiId());
                List<IesContractInfo> iesContractInfos = iesContractInfoMapper.selectByMap(p);
                if(iesContractInfos!=null&&iesContractInfos.size()>0){
                    IesContractStation ies=new  IesContractStation();
                    ies.setContractStationid(sf.nextId());
                    ies.setContractid(iesContractInfos.get(0).getContractid());
                    ies.setStationName(l.getEquipName());
                    ies.setStationinfoid(0L);
                    ies.setStationinfoids(l.getEquipFilezInfoId());
                    String voltlevel="";
                    if("01".equals(l.getElecLv())){
                        voltlevel="AC00101";
                    }
                    if("02".equals(l.getElecLv())){
                        voltlevel="AC00351";
                    }
                    if("03".equals(l.getElecLv())){
                        voltlevel="AC01101";
                    }
                    if("04".equals(l.getElecLv())){
                        voltlevel="AC02201";
                    }
                    ies.setVoltlevel(voltlevel);
                    ies.setCapacity(l.getEquipParaNo()==null?null:Integer.valueOf(l.getEquipParaNo()));
                    ies.setEmertype(l.getRepairCount());
                    ies.setAlreadynumber(l.getRepairExecunum()==null?null:Integer.valueOf(l.getRepairExecunum()));
                    if(ies.getEmertype()!=null&&ies.getAlreadynumber()!=null){
                        ies.setRemainnumber( Integer.valueOf(ies.getEmertype())-Integer.valueOf(ies.getAlreadynumber()));
                    }
                    iesContractStationMapper.insert(ies);
                }
            }else{
                //变压器
                Map<String,Object> p=new HashMap<>();
                p.put("contractids",l.getCiId());
                List<IesContractInfo> iesContractInfos = iesContractInfoMapper.selectByMap(p);
                if(iesContractInfos!=null&&iesContractInfos.size()>0){
                    IesConttransf ies=new IesConttransf();
                    ies.setDevlocation(l.getEquipName());
                    ies.setConttransfdevid(sf.nextId());
                    ies.setDevid(0L);
                    ies.setDevids(l.getEquipFilezInfoId());
                    ies.setContractid(iesContractInfos.get(0).getContractid());
                    String voltlevel="";
                    if("01".equals(l.getElecLv())){
                        voltlevel="AC00101";
                    }
                    if("02".equals(l.getElecLv())){
                        voltlevel="AC00351";
                    }
                    if("03".equals(l.getElecLv())){
                        voltlevel="AC01101";
                    }
                    if("04".equals(l.getElecLv())){
                        voltlevel="AC02201";
                    }

                    ies.setVoltlevel(voltlevel);
                    ies.setTransformercapacity(l.getEquipParaNo()==null||"".equals(l.getEquipParaNo())?null:Integer.valueOf(l.getEquipParaNo()));
                    ies.setDevtype("1401");
                    ies.setDevno(l.getEquipSeriesNo());
                    ies.setEmertype(l.getRepairCount());
                    ies.setAlreadynumber(l.getRepairExecunum()==null?null:Integer.valueOf(l.getRepairExecunum()));
                    if(ies.getEmertype()!=null&&ies.getAlreadynumber()!=null){
                        ies.setRemainnumber( Integer.valueOf(ies.getEmertype())-Integer.valueOf(ies.getAlreadynumber()));
                    }
                    iesConttransfMapper.insert(ies);
                }
            }
        });
        /**
         * 将合同关联的变压器、配电室表的id和 用户设备的cm_ar_equipment 表同步
         */
        iesConttransfMapper.synchronizationEquipId();
        iesContractStationMapper.synchronizationEquipId();
    }

    /**
     * 添加合同信息
     * @param sf
     */
    private void addIesContractInfo(SnowFlake sf) {
        List<TempContract> tempContracts = tempContractMapper.selectAll();
        tempContracts.forEach(t->{

            IesContractInfo iesContractInfo=new IesContractInfo();
            iesContractInfo.setContractid(sf.nextId());
            iesContractInfo.setContractids(t.getCiId());
            IesCust iesCust =iesCustMapper.selectCustId(t.getCustId());
            if(iesCust!=null){
                /**
                 * 客户标识
                 */
                iesContractInfo.setCustid(Long.valueOf(iesCust.getCustid()));
            }

            /**
             * 合同编号
             */
            iesContractInfo.setContractno(t.getCiNo());
            /**
             * 合同名称
             */
            iesContractInfo.setContractname(t.getCiName());
            /**
             * 签约地市
             */
            iesContractInfo.setPrefecturecity(t.getCiCityName()+t.getCiCountyName());
            /**
             * 客户名称
             */
            iesContractInfo.setCustname(t.getEntrustingParty());
            /**
             * 委托方名称（甲方，一般同客户名称）
             */
            iesContractInfo.setEntname(t.getEntrustingParty());
            /**
             * 服务商id
             */
           iesContractInfo.setServerid(0L);
            iesContractInfo.setServerids(t.getServicerId());
            /**
             * 套餐编码
             */
           /* combocode
                    contractpackagecode
            这两个字段
            21、24置为3
            23置为1
            22置为2
            04置为4
            */
            String ciSetMeal="";
            if("21".equals(t.getCiSetMeal())||"24".equals(t.getCiSetMeal())){
                ciSetMeal="3";//t.getCiSetMeal();
            }
            if("23".equals(t.getCiSetMeal())){
                ciSetMeal="1";//t.getCiSetMeal();
            }
            if("22".equals(t.getCiSetMeal())){
                ciSetMeal="2";//t.getCiSetMeal();
            }
            if("04".equals(t.getCiSetMeal())){
                ciSetMeal="4";//t.getCiSetMeal();
            }
            iesContractInfo.setCombocode(ciSetMeal);
            /**
             * 服务商名称
             */
            iesContractInfo.setServername(t.getServicerName());
            /**
             * 合同签订日期
             */
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                iesContractInfo.setSigndate(t.getCiSignDate()==null?null:dateFormat.parse(t.getCiSignDate()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            /**
             * 合同期限（年）
             */
            iesContractInfo.setContractperiod(t.getCiYear()==null?0:Integer.valueOf(t.getCiYear())/12);
            /**
             * 税额（元）
             */
            iesContractInfo.setTaxamount(0.00);
            /**
             * 合同金额（元）
             */
            iesContractInfo.setContractamt(t.getBeginMoney()==null?0.00:Double.valueOf(t.getBeginMoney()));
            /**
             * 合同套餐编码，铂金套餐、慧计量套餐、星会员
             */
            iesContractInfo.setContractpackagecode(ciSetMeal);
            /**
             * 乙方联系人电话
             */
            iesContractInfo.setServicetel("");
            /**
             * 乙方联系人
             */
            iesContractInfo.setServicepeople("");
            /**
             * 推广码
             */
            iesContractInfo.setPromotioncode(t.getSocEmpNo());
            String ciid = t.getCiId();
            Map<String,Object> p=new HashMap<>();
            p.put("ciId",ciid);
            List<TempContractInfo> tempContractInfos = tempContractInfoMapper.selectByMap(p);
            TempContractInfo tempContractInfo = tempContractInfos.get(0);
            /**
             * 开票状态编码，已开票、未开票
             */
            iesContractInfo.setInvoicstatus(tempContractInfo.getCiBillState());
            /**
             * 付款状态编码，已付款、未付款
             */
            iesContractInfo.setPaystatus(tempContractInfo.getCiPaymentState());
            /**
             * 合同状态编码，待下发、待确认，代收款、待开票
             */
            iesContractInfo.setConstatus(tempContractInfo.getCiContractState());
            /**
             * 客户修改状态
             */
            iesContractInfo.setModifystatus("");
            /**
             * 服务状态，服务中、已过期
             */
            String ciServiceState = tempContractInfo.getCiServiceState();
            String ciServiceStates="";
            if("01".equals(ciServiceState)){
                ciServiceStates="00";
            }
            if("03".equals(ciServiceState)){
                ciServiceStates="01";
            }
            if("04".equals(ciServiceState)){
                ciServiceStates="02";
            }
            iesContractInfo.setServerstatus(ciServiceStates);
            /**
             * 推广确认状态编码
             */
            iesContractInfo.setPromostatus(tempContractInfo.getPromoteState());
            /**
             * 服务起日期
             */
            try {
                iesContractInfo.setServerstartdate(tempContractInfo.getServiceBgn()==null?null:dateFormat.parse(tempContractInfo.getServiceBgn()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            /**
             * 服务止日期
             */
            try {
                iesContractInfo.setServerenddate(tempContractInfo.getServiceEnd()==null?null:dateFormat.parse(tempContractInfo.getServiceEnd()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            /**
             * 备注
             */
            iesContractInfo.setRemarks(t.getRemark());
            /**
             * 合同套餐名称
             */
            iesContractInfo.setContractpackagename(t.getCiSetMealName());
            /**
             * 是否已下发策略
             */
            iesContractInfo.setIsstrategy("");
            /**
             * 合同有效期开始时间
             */
            try {
                iesContractInfo.setEffstartdate(t.getCiEffectDate()==null?null:dateFormat.parse(t.getCiEffectDate()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            /**
             * 合同有效期结束时间
             */
            try {
                iesContractInfo.setEffenddate(t.getCiExpireDate()==null?null:dateFormat.parse(t.getCiExpireDate()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

            /**
             * 巡检次数
             */
            iesContractInfo.setRepairnum(0);
            Map<String,Object> p2=new HashMap<>();
            p2.put("ciId",t.getCiId());
            p2.put("priceType","05");
            List<TempPrice> tempPrices = tempPriceMapper.selectByMap(p2);
            /**
             * 慧计量服务定价
             */
            if(tempPrices!=null&&tempPrices.size()>0){
                iesContractInfo.setIntelligenprice(tempPrices.get(0).getPrice().doubleValue());
            }

            /**
             * 服务内容
             */
            iesContractInfo.setServiceitem("");
            /**
             * 巡检剩余次数
             */
            iesContractInfo.setRemainnumber(0);
            /**
             * 是否续签
             */
            iesContractInfo.setIsrenew(t.getIsRenew());
            /**
             * 结算模式编码
             */
            iesContractInfo.setSettlemodecode(t.getCiSettlModel());
            /**
             * 其它增值服务
             */
            iesContractInfo.setOtherserver("");
            /**
             * 特别约定
             */
            iesContractInfo.setSpecialpromise("");
            /**
             * 乙方联系电话
             */
            iesContractInfo.setPartybphone(t.getMobile());
            /**
             * 乙方联系人
             */
            iesContractInfo.setPartybperson(t.getContactName());
            /**
             * 创建时间
             */
            try {
                iesContractInfo.setCreateDate(t.getCreateTime()==null?null:dateFormat.parse(t.getCreateTime()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            /**
             * 创建用户
             */
            iesContractInfo.setCreateBy(t.getCreateUser());
            iesContractInfoMapper.insert(iesContractInfo);
        });
        iesContractInfoMapper.updateServerIdByName();
        iesContractInfoMapper.updateCustServerIdByName();
    }

    /**
     * 表ies_contract_consno (运维客户合同对应营销户号)
     */
    private void addIesContractConsno() {
        List<TempContractInfo> list=tempContractInfoMapper.selectAll();
        list.forEach(l->{
            Map<String,Object> param=new HashMap<>();
            param.put("contractids",l.getCiId());
            List<IesContractInfo> iesContractInfos = iesContractInfoMapper.selectByMap(param);
            String consno = l.getConsNo();
                    if(consno!=null){
                        String[] split = consno.split(",");
                        log.info("consno:{}",consno);
                        log.info("split:{}",split);
                        for(String s:split){
                            IesContractConsno iesContractConsno=new IesContractConsno();
                            iesContractConsno.setConsno(s);
                            iesContractConsno.setContractid(iesContractInfos.get(0).getContractid());
                            iesContractConsnoMapper.insert(iesContractConsno);
                        }
                    }
        });
        /**
         * 根据营销户号同步 营销户名称
         */
        iesContractConsnoMapper.updateConsName();
    }

}
